<?php

namespace App\Http\Controllers;

use App\Exceptions\AuthException;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use App\Services\AuthService;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /**
     * 注册
     *
     * @param RegisterRequest $request
     * @param AuthService $authService
     * @return array
     */
    public function register(RegisterRequest $request, AuthService $authService): array
    {
        $data = $request->only(['name', 'password']);

        try {
            $user = $authService->storeUser($data);
            if (! $user) {
                return $this->error('注册失败');
            }

            return $this->success('注册成功');
        } catch (AuthException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            return $this->error('注册失败，请重试');
        }
    }

    /**
     * 登录
     *
     * @param LoginRequest $request
     * @param AuthService $authService
     * @return array
     */
    public function login(LoginRequest $request, AuthService $authService): array
    {
        $data = $request->only(['name', 'password']);

        try {
            $user = $authService->loginByName($data);
            if (! $user) {
                return $this->error('登录失败');
            }

            return $this->success('登录成功');
        } catch (AuthException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            return $this->error('登录失败，请重试');
        }
    }

    public function logout(Request $request)
    {
        auth()->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return $this->success('退出成功');
    }
}
